<?php
// +----------------------------------------------------------------------
// | QSCMS
// +----------------------------------------------------------------------
// | Copyright (c)  2025 https://www.qqss.net All rights reserved.
// +----------------------------------------------------------------------
// | Licensed QSCMS is not free software, commercial use must purchase official license from official website to avoid unnecessary legal disputes.
// +----------------------------------------------------------------------
// | Author: Contract 990504246@qq.com
// +----------------------------------------------------------------------

namespace app\common\model;

use think\Model;

class GoodsContentGroup extends Model
{
    protected $autoWriteTimestamp = true;

    /**
     * 商品关联
     */
    public function goods()
    {
        return $this->belongsTo('Goods', 'goods_id');
    }

    /**
     * 章节关联
     */
    public function chapters()
    {
        return $this->hasMany('GoodsContentChapter', 'group_id')->order('sort asc, id asc');
    }

    /**
     * 获取指定商品的所有分组（包含章节）
     * @param int $goodsId 商品ID
     * @param bool $withChapterContent 是否包含章节内容
     * @return \think\Collection
     */
    public static function getGoodsGroups($goodsId, $withChapterContent = false)
    {
        $query = self::where('goods_id', $goodsId)
            ->order('sort asc, id asc');

        if ($withChapterContent) {
            $query->with(['chapters']);
        } else {
            $query->with(['chapters' => function ($query) {
                $query->field('id, group_id, title, sort, is_free');
            }
            ]);
        }

        return $query->select();
    }


}